package com.ruoyi.web.controller.ydz;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

import java.nio.charset.StandardCharsets;

@Controller
@RequestMapping("/ydz/push")
public class PushController {
    private String prefix = "ydz/push";

    @GetMapping("/baidu")
    public String baidu() {
        return prefix + "/baidu";
    }

    @GetMapping("/biying")
    public String biying() {
        return prefix + "/biying";
    }

    @RequestMapping("/pushBaidu")
    @ResponseBody
    public AjaxResult pushBaidu(@RequestParam String urls, @RequestParam String type) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            // 设置要推送的 URL
            String site = "";
            // PC端type = 01 M端type=02
            if ("01".equals(type)) {
                site = "https://www.1blv.cn";
            } else {
                site = "https://m.1blv.cn";
            }

            String token = "PXnHd1lfziq7O9ym";  // 请替换为你的 token
            String apiUrl = "http://data.zz.baidu.com/urls?site=" + site + "&token=" + token;
//            String decodedUrl = URLDecoder.decode(urlStr, String.valueOf(StandardCharsets.UTF_8)).substring(5);

            String[] urlsList = urls.split("\\r?\\n");

            // 需要推送的 URL 列表
            // String[] urls = {
            //         "https://www.1blv.com/newsDetail/128548.html",
            //         "https://www.1blv.com/newsDetail/128549.html"
            // };

            // 构建 POST 数据
            StringBuilder postData = new StringBuilder();
            for (String url : urlsList) {
                postData.append(url).append("\n");
            }

            // 创建 URL 对象
            URL url = new URL(apiUrl);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "text/plain");


            // 发送 POST 请求
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = postData.toString().getBytes("utf-8");
                os.write(input, 0, input.length);
            }
            // 获取响应
            int responseCode = connection.getResponseCode();
            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            JSONObject json = JSONObject.parseObject(response.toString());
            ajaxResult.put("code", "1");
            ajaxResult.put("data", json);
            System.out.println("Response Code: " + response.toString());

        } catch (IOException e) {
            e.printStackTrace();
            ajaxResult.put("code", "500");
            ajaxResult.put("msg", "推送失败，请联系管理员!");
        }
        return  ajaxResult;
    }

    @RequestMapping("/pushIndexnow")
    @ResponseBody
    public AjaxResult pushIndexnow(@RequestBody String urls) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            // 定义推送的 URL 和 API 密钥
            String apiUrl = "https://www.bing.com/indexnow";  // IndexNow 推送接口
            String apiKey = "5dd768d2452543e2b7b64babc4e3ec42";  // API 密钥
            String keyLocation = "https://www.1blv.cn/5dd768d2452543e2b7b64babc4e3ec42.txt";  // 要推送的 URL

            String decodedUrl = URLDecoder.decode(urls, String.valueOf(StandardCharsets.UTF_8)).substring(5);

            String[] urlList = decodedUrl.split("\\r?\\n");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("host", "www.1blv.cn");
            jsonObject.put("key", apiKey);
            jsonObject.put("keyLocation", keyLocation);
            jsonObject.put("urlList", urlList);

            // 构建请求体，包含 URL 和 API 密钥
            String body = String.valueOf(jsonObject);

            // 创建 URL 对象
            URL url = new URL(apiUrl);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为 POST
            connection.setRequestMethod("POST");
            // 设置允许输出
            connection.setDoOutput(true);
            // 设置请求头 Content-Type
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            // 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = body.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
            // 获取响应代码
            int responseCode = connection.getResponseCode();
            ajaxResult.put("code", responseCode);
            ajaxResult.put("msg", "推送成功!");
        } catch (IOException e) {
            e.printStackTrace();
            ajaxResult.put("code", "500");
            ajaxResult.put("msg", "推送失败，请联系管理员!");
        }
        return ajaxResult;
    }
}
